
let currentScope = null;
/**
 * @type {(scope:string) => void}
 */
let scopeUpdateListener = () => {};

function readScopeFromCookie() {
  let c = document.cookie;
  if (!c) {
    return null;
  }

  try {
    let o = JSON.parse(c);
    return (o != null) ? o.scope : null;
  } catch (e) {
    document.cookie = "";
    return null;
  }
}

/**
 * @returns {string} 
 */
function getScope(refresh = false) {
  if (currentScope == null || refresh) {
    readScopeFromCookie();
  }
  return currentScope;
}

function setScope(scope) {
  document.cookie = JSON.stringify({ scope : scope });
  currentScope = scope;
  scopeUpdateListener(scope);
}

/**
 * @param {(scope:string) => void} l 
 */
function setScopeUpdateListener(l) {
  if (typeof(l) == 'function') {
    scopeUpdateListener = l;
  }
}

export default { getScope, setScope, setScopeUpdateListener };

